package com.xiaode.cronTask;

import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.cron4j.ITask;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.mysql.jdbc.Connection;
import com.xiaode.common.constant.Const;
import com.xiaode.common.model.*;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

/**
 * 统计每月之星
 * 每月有通过发帖和回复的上限分数
 * 月度之星的积分 和 积分是两个分
 * 积分是学生做各种任务来的
 * 月度之星的积分是用来月度之星排名的
 * 月度之星的积分是 积分+ 老师推荐*5 + 发帖/回复*2
 */
public class Statistics implements ITask {
    @Override
    public void stop() {

    }


    @Override
    public void run() {
    	System.out.println("执行每月统计-----------------------------");
        Cache redis = Redis.use();
//        //每月之星 月积分+教师推荐次数*5+发帖数*2
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime localDateTime = now.minusMonths(1);
        LocalDateTime firstDay = localDateTime.with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime lastDay = localDateTime.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
        Set<String> keys = redis.keys(Const.user.Student + "*");
        ArrayList<Student> studnetList = new ArrayList<>(830);
        for (String key : keys) {
            studnetList.add(redis.get(key));
        }
        //事务处理添加每月之星与积分rank
        Db.tx(Connection.TRANSACTION_REPEATABLE_READ,()->{
            try {
	            //保存积分榜单
	            @SuppressWarnings("unchecked")
				Set<Integer> zrange = redis.zrange(Const.user.StudentScore, 0, -1);
	            ArrayList<ScoreRank> scoreRanks = new ArrayList<>();
	            for (Integer id : zrange) {
	                Double zscore = redis.zscore(Const.user.StudentScore, id);
	                ScoreRank scoreRank = new ScoreRank();
	                scoreRank.setStudentId(id);
	                scoreRank.setScore(zscore.intValue());
	                scoreRanks.add(scoreRank);
	            }
	            Db.batchSave(scoreRanks, scoreRanks.size());
	
	            ArrayList<MonthStar> monthStars = new ArrayList<MonthStar>();
            
                int[] gradeIds = {1,2,5};//高二，高三，高一
                for (int i=0; i<gradeIds.length; i++) {
                	List<Integer> classIdList = Db.query("SELECT id FROM org_class WHERE adminGradeId = ?", gradeIds[i]);
                	List<Record> recordList = Db.template("findStudentIdsByClass", Kv.of("clasIds", classIdList)).find();
                	for(Record record : recordList) {
                		Kv kv = Kv.of("id", record.getInt("id")).set("startTime", firstDay).set("endTime", lastDay);
                		Record jfSum = Db.template("findStudentMarkLog", kv).findFirst();
                		int mjf = jfSum.getInt("sum");
                		int tjcount = Db.queryInt("SELECT COUNT(*) count FROM campus_share_teacher_recommend WHERE create_account_id = ? AND add_time BETWEEN ? AND ?", record.getInt("accountId"), firstDay, lastDay);
                		int yccount = Db.queryInt("SELECT COUNT(*) count FROM campus_share_original WHERE user_account_id = ? AND add_time BETWEEN ? AND ?", record.getInt("accountId"), firstDay, lastDay);
                		int commentsCount = Db.queryInt("SELECT COUNT(*) count FROM campus_share_comments WHERE create_account_id = ? AND addTime BETWEEN ? AND ?", record.getInt("accountId"), firstDay, lastDay);
                		int addMark = (yccount + commentsCount) * 2;
                    	addMark = Const.monthMaxMark < addMark ? Const.monthMaxMark : addMark;
                		int sum = mjf + tjcount*5 + addMark;
                		record.set("sum", sum);
                	}
                    //如果记录为空直接进入下个循环
                    if (recordList == null || recordList.size() == 0){
                        continue;
                    }
                    Collections.sort(recordList, new Comparator<Record>() {
                        @Override
                        public int compare(Record r1, Record r2) {
                            return r2.getInt("sum") - r1.getInt("sum");
                        }
                    });
                    //添加排名并做集合
                    int rank = 1;
                    Double sum = Math.ceil(recordList.get(0).getDouble("sum"));
                    int score = sum.intValue();
                    for (Record record1 : recordList) {
                        MonthStar monthStar = new MonthStar();
                        monthStar.setStudentId(record1.getInt("id"));
                        //排名逻辑
                        int mySum = ((Double)Math.ceil(record1.getDouble("sum"))).intValue();
                        if (mySum < score){
                            score = mySum;
                            rank += 1;
                        }
                        monthStar.setRank(rank);
                        monthStar.setScore(record1.getDouble("sum").intValue());
                        monthStars.add(monthStar);
                    }
                }

                Db.batchSave(monthStars, monthStars.size());
            }catch (Exception e){
            	e.printStackTrace();
                return false;
            }
            return true;
        });
        System.out.println("执行每月统计完成-----------------------------");
    }
    
    
}
